<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
Type an expression in the following box (e.g., 10.5+20*3/25).
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>

<ul>
<li>Only numbers and +,-,* and / operators are allowed in the expression.
<li>The evaluation follows the standard operator precedence.
<li>The calculator does not support parentheses.
<li>The calculator handles invalid input "gracefully". It does not output PHP error messages.
</ul>
Here are some assumptions:
<ol>
	<li> All fractional numbers will have a leading zero </li>
	<li> We will not support any positive sign before a number, but a negative sign needs to be supported. For example, we may test expressions like "3*-2" or "-2/-3" or "1+-1".</li>
</ol>
Here are some(but not limit to) reasonable test cases:
<ol>
  <li> A basic arithmetic operation:  3+4*5=23 </li>
  <li> An expression with floating point or negative sign : -3.2+2*4-1/3 = 4.46666666667, 3+-2.1*2 = -1.2 </li>
  <li> Some typos inside operation (e.g. alphabetic letter): Invalid input expression 2d4+1 </li>
</ol>
</body>
</html>

<?php

$equ = $_GET["expr"];
$origequ = $equ;
$equ = preg_replace('/\s+/', '', $equ); // remove whitespaces

//$number = '(?:\d+(?:[,.]\d+)?)'; // What is a number

//$regexpr = '#[+-]?(\d+(\.\d+)?|[a-z]\w*)([+*/-][+-]?(\d+(\.\d+)?)|[a-z]\w*)*#';
//$regexpr = '#^([+-]?(?:\d+(?:[,.]\d+)?))([+*/-][+-]?(?:\d+(?:[,.]\d+)?))*#';
$regexpr = '#^([-]?(?:\d+(?:[,.]\d+)?))([+*/-][-]?(?:\d+(?:[,.]\d+)?))*#';
//$regexpr = '#^([+-]?(\d+(\.\d+)?))([+*/-][+-]?(\d+(\.\d+)?))*#';
//echo $regexpr;
//if ( preg_match( '#^([0-9]+)(+-*/[0-9]+)*#', $equ) ) {
if ($equ == '')
{
	echo "";
}
elseif ( preg_match ('#/0#', $equ))
{
	echo "Invalid Expression (divided by 0): ".$origequ;
}
elseif ( preg_match ('#[a-z]\w*#', $equ) )
{
	echo "Invalid Expression: ".$origequ;
}
elseif ( preg_match ('#[A-z]\w*#', $equ) )
{
	echo "Invalid Expression: ".$origequ;
}
//elseif ( preg_match ('##', $equ) )
//{
//	echo "Invalid Expression: ".$origequ;
//}
elseif ( preg_match( $regexpr, $equ, $out) ) {
//if ( preg_match( $regexp, $equ) ) {
//	print $out[0]."\n";
	if ($out[0] == $equ)
	{
		$equ = preg_replace('#--#', '+', $equ);
		echo "Result: ";
		eval("\$ans = $equ;");
		echo $origequ." = ".$ans;
	}
	else
	{
		echo "Invalid Expression: ".$origequ;
	}
}
else
{
	echo "Invalid Expression: ".$origequ;
}
?>
